package com.liyu.iblog.dao.jpa;

import java.util.List;

import javax.persistence.EntityManager;

import org.springframework.stereotype.Repository;

import com.google.appengine.api.datastore.KeyFactory;
import com.liyu.iblog.dao.CommentDao;
import com.liyu.iblog.domain.Blog;
import com.liyu.iblog.domain.Comment;

@Repository("commentDao")
public class CommentDaoJpa extends GenericDaoJpa<Comment> implements CommentDao {

    public CommentDaoJpa() {
        super(Comment.class);
    }

    @Override
    public List<Comment> getCommentsByBlogKey(Object blogKey) {
        EntityManager em = emf.createEntityManager();
        List<Comment> comments = null;
        try {
            Blog blog = em.find(Blog.class, blogKey);
            // works this way
            //comments = new ArrayList<Comment>(blog.getComments());
            if (blog != null) {
                comments = blog.getComments();
                /* force the lazy loading collection to be loaded, 
                 * populate the encoded key if the comment doesn't have one
                 */
                for (Comment c : comments) 
                    if (c.getEncodedKey() == null) 
                        c.setEncodedKey(KeyFactory.keyToString(c.getKey()));
                
                //check if the blog comment count equals the actual commnet number
                if (blog.getCommentCount() != comments.size())
                    blog.setCommentCount(comments.size());
            }
        } catch(Exception e) {
            e.printStackTrace();
        } finally {
            em.close();
        }
        return comments;
    }

}
